package com.sws.web.controller.student_attendance.person;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sws.device.service.DeviceIpResolverService;
import jakarta.servlet.http.HttpServletResponse;


import com.sws.common.exception.ServiceException;
import com.sws.common.utils.access_tokenutil.util.AccessTokenUtil;
import com.sws.person.ball.CameraServerProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.sws.common.annotation.Log;
import com.sws.common.core.controller.BaseController;
import com.sws.common.core.domain.AjaxResult;
import com.sws.common.enums.BusinessType;
import com.sws.person.domain.PerPerson;
import com.sws.person.service.IPerPersonService;
import com.sws.common.utils.poi.ExcelUtil;
import com.sws.common.core.page.TableDataInfo;
import org.springframework.web.client.RestTemplate;
import com.sws.rel.service.IPersonDeviceRelService;

/**
 * 人员信息Controller
 * 
 * @author cx
 * @date 2025-06-09
 */
@Api(tags = {"人员信息Controller"})
@RestController
@RequestMapping("/student/person/person")
public class PerPersonController extends BaseController
{
    @Autowired
    private IPerPersonService perPersonService;

    @Autowired
    private CameraServerProperties cameraServerProperties; // 注入配置
    
    @Autowired
    private RestTemplate restTemplate; // 注入配置好的RestTemplate

    @Autowired
    private DeviceIpResolverService deviceIpResolverService;

    @Autowired
    private IPersonDeviceRelService personDeviceRelService;

    /**
     * 查询人员信息列表
     */
    @ApiOperation("查询人员信息列表")
    @PreAuthorize("@ss.hasPermi('person:person:list')")
    @GetMapping("/list")
    public TableDataInfo list(PerPerson perPerson)
    {
        startPage();
        List<PerPerson> list = perPersonService.selectPerPersonList(perPerson);
        // 为每条记录动态添加前缀
        list.forEach(p -> p.setPhoto(perPersonService.convertToFullUrl(p.getPhoto())));
        return getDataTable(list);
    }

    /**
     * 导出人员信息列表
     */
    @ApiOperation("导出人员信息列表")
    @PreAuthorize("@ss.hasPermi('person:person:export')")
    @Log(title = "人员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PerPerson perPerson)
    {
        List<PerPerson> list = perPersonService.selectPerPersonList(perPerson);
        ExcelUtil<PerPerson> util = new ExcelUtil<PerPerson>(PerPerson.class);
        util.exportExcel(response, list, "人员信息数据");
    }

    /**
     * 获取人员信息详细信息
     */
    @ApiOperation("获取人员信息详细信息")
    @PreAuthorize("@ss.hasPermi('person:person:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        PerPerson person = perPersonService.selectPerPersonById(id);
        // 返回前端时动态添加前缀
        person.setPhoto(perPersonService.convertToFullUrl(person.getPhoto()));
        
        // 查询此人员关联的所有设备
        if (person.getPid() != null && !person.getPid().isEmpty()) {
            List<String> deviceSns = personDeviceRelService.getDeviceSnsByPersonPid(person.getPid());
            person.setDeviceIds(deviceSns);
        }
        
        return success(person);
    }

    /**
     * 新增人员信息
     */
    @ApiOperation("新增人员信息")
    @PreAuthorize("@ss.hasPermi('person:person:add')")
    @Log(title = "人员信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PerPerson perPerson) {
        try {
            // 检查设备ID列表是否提供
            if (perPerson.getDeviceIds() == null || perPerson.getDeviceIds().isEmpty()) {
                return error("请至少选择一个设备");
            }
            
            // 添加人员到选择的所有设备（会在service层生成随机PID）
            PerPerson devicePerson = perPersonService.addPersontoCamera(perPerson);

            // 设备返回的图片路径已经在service中添加了前缀，直接使用
            perPerson.setPhoto(devicePerson.getPhoto());
            
            // 确保PID已经设置
            perPerson.setPid(devicePerson.getPid());
            
            // 设置deviceId为第一个设备ID（作为主设备）
            if (perPerson.getDeviceIds() != null && !perPerson.getDeviceIds().isEmpty()) {
                perPerson.setDeviceId(perPerson.getDeviceIds().get(0));
            }

            // 保存到数据库
            int result = perPersonService.insertPerPerson(perPerson);
            perPerson.setPhoto(perPersonService.convertToFullUrl(perPerson.getPhoto()));
            
            return result > 0 ? 
                success("成功添加人员到 " + perPerson.getDeviceIds().size() + " 个设备") : 
                error("添加数据库失败");
        } catch (ServiceException e) {
            logger.error("添加人员到设备失败", e);
            return error("设备操作失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("添加人员失败", e);
            return error("系统错误: " + e.getMessage());
        }
    }

    /**
     * 修改人员信息
     */
    @ApiOperation("修改人员信息")
    @PreAuthorize("@ss.hasPermi('person:person:edit')")
    @Log(title = "人员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PerPerson perPerson) {
        try {
            // 检查设备ID列表是否提供
            if (perPerson.getDeviceIds() == null || perPerson.getDeviceIds().isEmpty()) {
                return error("请至少选择一个设备");
            }
            
            // 设置deviceId为第一个设备ID（作为主设备）
            perPerson.setDeviceId(perPerson.getDeviceIds().get(0));

            int result = perPersonService.updatePerPerson(perPerson);
            return toAjax(result);
        } catch (ServiceException e) {
            logger.error("更新人员信息失败", e);
            return error("更新失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("系统错误", e);
            return error("系统错误: " + e.getMessage());
        }
    }


    /**
     * 删除人员信息
     */
    @ApiOperation("删除人员信息")
    @PreAuthorize("@ss.hasPermi('person:person:remove')")
    @Log(title = "人员信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        try {
            int result = perPersonService.deletePerPersonByIds(ids);
            if (result == ids.length) {
                return success();
            } else {
                return error("部分删除成功，共处理" + result + "/" + ids.length + "条数据");
            }
        } catch (ServiceException e) {
            return error(e.getMessage());
        }
    }


    /**
     * 同步摄像头服务器人员信息（支持多设备）
     */
    @ApiOperation("同步摄像头服务器人员信息（支持多设备）")
    @PreAuthorize("@ss.hasPermi('person:person:sync')")
    @Log(title = "人员信息", businessType = BusinessType.INSERT)
    @PostMapping("/syncFromCameraServer")
    public AjaxResult syncFromCameraServer(@RequestBody Map<String, Object> requestMap) {
        try {
            List<String> sns = new java.util.ArrayList<>();
            Object snsObj = requestMap.get("sns");
            
            // 处理不同类型的输入
            if (snsObj instanceof List) {
                // 如果是列表，直接转换
                for (Object item : (List<?>) snsObj) {
                    if (item instanceof String) {
                        sns.add((String) item);
                    }
                }
            } else if (snsObj instanceof String) {
                // 如果是单个字符串，添加到列表
                sns.add((String) snsObj);
            }
            if (sns.isEmpty()) {
                return error("请至少选择一个设备");
            }
            
            int totalSuccess = 0;
            StringBuilder errors = new StringBuilder();
            
            // 遍历所有设备进行同步
            for (String sn : sns) {
                try {
                    // 使用配置值动态构建URL
                    String url = cameraServerProperties.getBaseUrlBySn(sn) + "/cgi-bin/jvsweb.cgi?cmd=";

                    HttpHeaders headers = new HttpHeaders();
                    String accessToken = AccessTokenUtil.getTokenBySn(sn, deviceIpResolverService);
                    headers.set("Cookie", "language=zh; username=admin; Access-Token=" + accessToken);

                    // 优化后的请求体构造
                    Map<String, Object> requestParam = new HashMap<>();
                    requestParam.put("channelid", 0);
                    requestParam.put("page_size", 32); // 增加每页数量，避免分页问题
                    requestParam.put("search_db", true);

                    Map<String, Object> requestBody = new HashMap<>();
                    requestBody.put("uri", "/person/list");
                    requestBody.put("param", requestParam);

                    // 发送请求
                    HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
                    ResponseEntity<Map> response = restTemplate.postForEntity(url, requestEntity, Map.class);
                    
                    // 处理单个设备的响应
                    if (response.getStatusCode().is2xxSuccessful()) {
                        Map<String, Object> responseBody = response.getBody();
                        if (responseBody != null && "0".equals(String.valueOf(responseBody.get("code")))) {
                            Map<String, Object> result = (Map<String, Object>) responseBody.get("result");
                            List<Map<String, Object>> personList = (List<Map<String, Object>>) result.get("list");
                            
                            if (personList != null && !personList.isEmpty()) {
                                int successCount = perPersonService.syncPersonsFromCamera(personList, sn);
                                totalSuccess += successCount;
                                logger.info("设备 {} 同步成功，处理 {} 条数据", sn, successCount);
                            }
                        } else {
                            String errorMsg = responseBody != null && responseBody.containsKey("msg") ?
                                    responseBody.get("msg").toString() : "未知错误";
                            errors.append("设备 ").append(sn).append(" 返回错误：").append(errorMsg).append("; ");
                        }
                    } else {
                        errors.append("设备 ").append(sn).append(" 响应状态异常：").append(response.getStatusCode()).append("; ");
                    }
                } catch (Exception e) {
                    logger.error("同步设备 {} 失败", sn, e);
                    errors.append("设备 ").append(sn).append(" 同步异常：").append(e.getMessage()).append("; ");
                }
            }
            
            // 返回结果
            if (errors.length() > 0) {
                return success("同步部分完成，成功处理 " + totalSuccess + " 条数据，错误信息：" + errors.toString());
            } else {
                return success("同步成功，共处理 " + totalSuccess + " 条数据");
            }
        } catch (Exception e) {
            logger.error("同步失败", e);
            return error("同步失败：" + e.getMessage());
        }
    }

    /**
     * 获取所有人员列表
     */
    @ApiOperation("获取所有人员列表")
    @GetMapping("/all")
    @ResponseBody
    public AjaxResult getAllPersonList() {
        PerPerson person = new PerPerson();
        person.setDelFlag(0); // 只查询未删除的人员
        List<PerPerson> list = perPersonService.selectPerPersonList(person);
        return AjaxResult.success(list);
    }
}

